package game.controller;

import game.model.Block;
import game.model.Board;

import java.util.LinkedList;
import java.util.Queue;

public class NormalMove implements MoveRule {
    @Override
    public boolean moveBlocks(final Board board, Direction direction) {
        // 处理时，程序会依次逆时针旋转 90 度，旋转第 cnt 次前调用 moveLeft
        int cnt;
        if (direction == Direction.LEFT) cnt = 1;
        else if (direction == Direction.UP) cnt = 2;
        else if (direction == Direction.RIGHT) cnt = 3;
        else if (direction == Direction.DOWN) cnt = 4;
        else return false;

        // 开始处理
        boolean ret = false;
        // 拷贝一份
        Board nexBoard = new Board(board.getWidth(), board.getHeight());
        nexBoard.copiedBy(board);
        // 依次逆时针旋转 90 度
        for (int i = 1; i <= 4; ++i) {
            if (cnt == i) ret = this.moveLeft(nexBoard);
            nexBoard = Board.rotateBoard90Degree(nexBoard);
        }
        board.copiedBy(nexBoard);
        return ret;
    }



    /**
     * 对指定棋盘执行操作：向左移动方块
     *
     * @param board
     * @return 是否有方块成功移动
     */
    private boolean moveLeft(Board board) {
        int cnt = 0;
        for (int y = 0; y < board.getHeight(); ++y) {
            Queue<Integer> qe = new LinkedList<Integer>(); // 记录这一行的空位置
            for (int x = 0; x < board.getWidth(); ++x) {
                if (board.getBlock(x, y) == null) { // 当前位置为空，那么将其将入队列
                    qe.add(x);
                } else { // 当前位置不为空
                    if (qe.isEmpty()) { // 队列为空，说明左侧已经塞满
                        continue;
                    }
                    // 将当前位置的方块移动到队首标记的位置，并将当前位置放入队列
                    board.setBlock(qe.poll(), y, board.getBlock(x, y));
                    board.setBlock(x, y, null);
                    qe.add(x);
                    ++cnt;
                }
            }
        }
        return cnt > 0;
    }
}
